/**
 * 序列化带函数的对象
 * @param {*} obj       序列化对象
 * @param {*} variable  变量名称
 * @returns
 */
export function serialize (obj, variable = 'obj') {
  let result = `var=${variable}`
  function serializeInternal (o, path) {
    for (let p in o) {
      let value = o[p]
      if (typeof value != 'object') {
        if (typeof value == 'string') {
          result += '\n' + path + '[' + (isNaN(p) ? '"' + p + '"' : p) + '] = ' + '"' + value.replace(/\"/g, '\\"') + '"' + ';'
        } else {
          result += '\n' + path + '[' + (isNaN(p) ? '"' + p + '"' : p) + '] = ' + value + ';'
        }
      } else {
        if (Array.isArray(value)) {
          result += '\n' + path + '[' + (isNaN(p) ? '"' + p + '"' : p) + ']' + '=' + 'new Array();'
          serializeInternal(value, path + '[' + (isNaN(p) ? '"' + p + '"' : p) + ']')
        } else {
          result += '\n' + path + '[' + (isNaN(p) ? '"' + p + '"' : p) + ']' + '=' + 'new Object();'
          serializeInternal(value, path + '[' + (isNaN(p) ? '"' + p + '"' : p) + ']')
        }
      }
    }
  }
  serializeInternal(obj, variable)
  return result
}

/**
 * 反序列化带函数的字符串
 * @param {*} str 反序列化字符串
 */
export function deserialize (str) {
  const variable = str.substring(0, str.indexOf('\n')).split('=')[1]
  window[variable] = {}
  eval(str.replace(str.substring(0, str.indexOf('\n')), ''))
  const obj = window[variable]
  delete window[variable]
  return obj
}